import numpy as np
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体显示中文
plt.rcParams['axes.unicode_minus'] = False    # 正常显示负号

# 参数化路径 gamma: 从 0 到 1+i
# z(t) = (1+i) * t, t in [0,1]
def parametric_path(t):
    return (1 + 1j) * t

def derivative_path(t):
    return (1 + 1j)

# 被积函数 f(z) = Re(z) = x
def integrand(z):
    return np.real(z)

# 数值积分
def complex_line_integral():
    # 使用(高精度的)数值积分
    t = np.linspace(0, 1, 100)
    z = parametric_path(t)
    dz = derivative_path(t) * (t[1] - t[0])
    
    # 计算积分 sum(f(z) * dz)
    integral = np.sum(integrand(z) * dz)
    return integral

result = complex_line_integral()
# print(f"沿从0到1+i的直线段的积分值: {result}")

print(f"沿从0到1+i的直线段的积分值: {result.real:.4f} + {result.imag:.4f}j")

# 解析解：积分 = int_0^1 t * (1+i) dt = (1+i) * [t^2/2]_0^1 = (1+i)/2
analytical_result = (1 + 1j) / 2
print(f"解析解: {analytical_result}")
err = abs(result - analytical_result)
print(f"误差: {err:.4f}")
